<?php
declare(strict_types=1);

namespace App\Admin\Controller;
use App\Common\Controller\AbstractController;
use App\Common\Validate\Validate;
use Hyperf\Di\Annotation\Inject;
use App\Admin\Validate\CommonValidate;
use App\Server\Model\Admin;
use Hyperf\Validation\ValidatorFactory;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Hyperf\HttpMessage\Cookie\Cookie;
use Hyperf\Paginator\Paginator;
class CommonController extends AbstractController
{
    public function test(\Hyperf\Filesystem\FilesystemFactory $factory){

        $ab = config('file.storage.qiniu');

        $qiniu = $factory->get('qiniu');

        $qiniu->write('posts/20200455/file.txt', 'contents');

    }


    /**
     * @Inject()
     * @var CommonValidate
     */
    protected $CommonValidate;


    /**
     * 管理员退出，清除名字为admin的session
     * @return [type] [description]
     */
    public function logout()
    {
        $this->session->clear();
        $cookie = new Cookie('admin', '');
        if($this->session->has('admin')) {
            return $this->error('退出失败')->withCookie($cookie);
        } else {
            return $this->success(['url'=>'/admin/common/login'],'正在退出...')->withCookie($cookie);
        }
    }

    /**
     * 登录
     * @return Psr7ResponseInterface
     */
    public function login(): Psr7ResponseInterface
    {
        $model = new Admin();
        $method = $this->request->getMethod();
        if($this->session->get('admin') == false) {
            if($method=='POST') {
                //是登录操作
                $post = $this->request->post();
                $errorMessage = $this->CommonValidate->login($this->request);
                //验证部分数据合法性
                if ($errorMessage) {
                    return $this->error('提交失败：' . $errorMessage);
                }
                $where=[];
                $where [] = ['name','=',$post['name']];
                $field = ['id','password'];
                $name = $model -> getInfo($where,$field);

                if(empty($name)) {
                    //不存在该用户名
                    return $this->error('用户名不存在');
                } else {
                    //验证密码
                    $post['password'] = password($post['password']);
                    if($name['password'] != $post['password']) {
                        return $this->error('密码错误');
                    } else {
                        unset($name['password']);
                        //是否记住账号
                        if(!empty($post['remember']) and $post['remember'] == 1) {
                            //检查当前有没有记住的账号
                            $cookie = new Cookie('admin',serialize($name));
                        } else {
                            //未选择记住账号，或属于取消操作
                            $cookie = new Cookie('admin', '');
                        }
                        //保存新的
                        $this->session->set('admin',$name);
                        //记录登录时间和ip
                        $where=[];
                        $where [] = ['id','=',$name['id']];
                        $model -> dataUpdate($where,['login_ip' =>  getClientIp(),'login_time' => time()]);
                        //记录操作日志
                        addlog($this->request,$name['id'],'用户登录');
                        return $this->success(['url'=>'/admin/index/index'],'登录成功,正在跳转...')->withCookie($cookie);
                    }
                }
            } else {
                if($this->request->cookie('admin')) {
                    $cookie = new Cookie('admin', $this->request->cookie('admin'));
                }
                if (isset($cookie)){
                    $name = unserialize($this->request->cookie('admin'));
                    $this->session->set('admin',$name);
                    return $this->response->redirect('admin/common/login');
                }else{
                    return $this->render->render('/admin/common/login');
                }
            }
        } else {
            return $this->response->redirect('admin/index/index');
        }
    }

    /**
     * 清除全部缓存
     * @return [type] [description]
     */
    public function clear()
    {
        $resa = new \App\Server\Cache\Cache();
        $keys = [
            'webconfig_web',     //网站配置
            'webconfig_email',     //网站配置
            'webconfig_sms',     //网站配置
            'display_menu',  //需要展示的菜单
            'menu_all',      //后台所有菜单
        ];
        $clearRes = $resa->deleteMultiple($keys);
        if(false == $clearRes) {
        	return $this->error('清除缓存失败');
        } else {
        	return $this->success([],'清除缓存成功');
        }
    }

}
